﻿using System;
using System.Text;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace Com.Web.coffinegurunaru.AppLogic
{
	public class NaverAPI
	{
		public static string GetAPIKey()
		{
			if (HttpContext.Current != null)
			{
				HttpRequest req = HttpContext.Current.Request;
				if (req.Url.ToString().ToLower().IndexOf("www.coffine.co.kr") != -1)
				{
					return "718d3bcc4956943d60c75fcd46ed481e";
				}
				else if (req.Url.ToString().ToLower().IndexOf("gurunaru2.cafe24.com") != -1)
				{
					return "a7d901fce681399e503145d36d39eb5c";
				}
			}

			return string.Empty;
		}

		public static string GetGEOCode(string Address)
		{
			Address = Address.Replace(" ", "");
			string url = string.Format("http://maps.naver.com/api/geocode.php?key={0}&query={1}", GetAPIKey(), HttpUtility.UrlEncode(Address, Encoding.GetEncoding("euc-kr")));

			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
			HttpWebResponse res = (HttpWebResponse)req.GetResponse();
			StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("euc-kr"));
			string resString = reader.ReadToEnd();
			reader.Close();
			res.Close();

			return resString;
		}

		public static List<NaverAPIPointInfo> ParseGEOCode(string XmlContent)
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(XmlContent);

			XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
			namespaceManager.AddNamespace("myprefix", "naver:openapi");

			List<NaverAPIPointInfo> retVal = new List<NaverAPIPointInfo>();
			foreach (XmlNode node in doc.SelectNodes("//myprefix:item", namespaceManager))
			{
				string pointX = node.SelectSingleNode("myprefix:point/myprefix:x", namespaceManager).InnerText;
				string pointY = node.SelectSingleNode("myprefix:point/myprefix:y", namespaceManager).InnerText;

				string address = node.SelectSingleNode("myprefix:address", namespaceManager).InnerText;

				NaverAPIPointInfo item = new NaverAPIPointInfo()
				{
					PointX = pointX,
					PointY = pointY,
					Address = address
				};

				retVal.Add(item);
			}

			return retVal;
		}
	}
}
